package org.example.rzfx.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.rzfx.entity.CollectMonitor;
import org.example.rzfx.mapper.CollectMonitorMapper;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;

/**
 * 采集监控服务
 */
@Service
public class CollectMonitorService extends ServiceImpl<CollectMonitorMapper, CollectMonitor> {
    
    /**
     * 更新采集成功数
     */
    public void incrementSuccess(Long sourceId) {
        CollectMonitor monitor = getOrCreate(sourceId);
        monitor.setSuccessCount(monitor.getSuccessCount() + 1);
        monitor.setLastCollectTime(LocalDateTime.now());
        monitor.setLastHeartbeat(LocalDateTime.now());
        this.updateById(monitor);
    }
    
    /**
     * 更新采集失败数
     */
    public void incrementFail(Long sourceId, String errorMsg) {
        CollectMonitor monitor = getOrCreate(sourceId);
        monitor.setFailCount(monitor.getFailCount() + 1);
        monitor.setErrorMsg(errorMsg);
        monitor.setLastCollectTime(LocalDateTime.now());
        monitor.setLastHeartbeat(LocalDateTime.now());
        this.updateById(monitor);
    }
    
    /**
     * 获取或创建监控记录
     */
    private CollectMonitor getOrCreate(Long sourceId) {
        LambdaQueryWrapper<CollectMonitor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CollectMonitor::getSourceId, sourceId);
        CollectMonitor monitor = this.getOne(wrapper);
        
        if (monitor == null) {
            monitor = new CollectMonitor();
            monitor.setSourceId(sourceId);
            monitor.setSuccessCount(0);
            monitor.setFailCount(0);
            monitor.setLastHeartbeat(LocalDateTime.now());
            this.save(monitor);
        }
        
        return monitor;
    }
}

